﻿#define _CRT_SECURE_NO_WARNINGS 1
#include "SeqList.h"


void SLInit(Seqlist* s)
{
	s->seqlist = NULL;
	s->size = 0;
	s->counst = 0;
}

void SLDestroy(Seqlist* s)
{
	free(s->seqlist);
	s->seqlist = NULL;
	s->size = 0;
	s->counst = 0;
}

void SLPushBack(Seqlist* s, seqclass x) {
	assert(s);
	SLCheckCapacity(s);
	s->seqlist[s->counst] = x;
	s->counst++;
	return;
}

void SLPushFront(Seqlist* s, seqclass x)
{
	assert(s);
	SLCheckCapacity(s);
	s->counst++;
	for (int i = s->counst; i > 0; i--)
	{
		s->seqlist[i] = s->seqlist[i - 1];
	}
	s->seqlist[0] = x;
	return;
}

void SLPrint(const Seqlist* s)
{
	assert(s);
	for (int i = 0; i < s->counst; i++)
	{
		printf("%d ", s->seqlist[i]);
	}
	printf("\n");
	return;
}

void SLPopBack(Seqlist* s)
{
	assert(s);
	assert(s->counst);
	s->counst--;

	SLCut(s);

	return;
}

void SLPopFront(Seqlist* s)
{
	assert(s);
	assert(s->counst);
	s->counst--;
	for (int i = 0; i < s->counst; i++)
	{
		s->seqlist[i] = s->seqlist[i + 1];
	}

	SLCut(s);

	return;
}

void SLCheckCapacity(Seqlist* s)
{
	if (s->seqlist)
	{
		if (s->counst == s->size)
		{
			seqclass* ret = (seqclass*)realloc(s->seqlist, sizeof(seqclass) * 2 * s->size);
			if (ret == NULL)
			{
				exit(-1);
			}
			s->seqlist = ret;
			ret = NULL;
			s->size *= 2;
		}

	}
	else
	{
		seqclass* ret = (seqclass*)malloc(sizeof(seqclass) * 4);
		if (ret == NULL)
		{
			exit(-1);
		}
		s->seqlist = ret;
		ret = NULL;
		s->size = 4;
	}
	return;
}

void SLCut(Seqlist* s)
{
	if (s->counst == (s->size) / 2 && s->size > 4)
	{
		seqclass* ret = (seqclass*)realloc(s->seqlist, sizeof(seqclass) * s->size / 2);
		if (ret == NULL)
		{
			perror("SLPushFront");
			exit(-1);
		}
		s->size /= 2;
	}
}

int SLFind(Seqlist* s, seqclass x)
{
	assert(s);
	for (int i = 0; i < s->counst; i++)
	{
		if (s->seqlist[i] == x)
		{
			return i;
		}
	}
	return -1;
}

void SLInsert(Seqlist* s, int pos, seqclass x)
{
	assert(s);
	assert(pos >= 0 && pos <= s->counst);
	SLCheckCapacity(s);
	s->counst++;
	for (int i = s->counst; i > pos; i--)
	{
		s->seqlist[i] = s->seqlist[i - 1];
	}
	s->seqlist[pos] = x;
	return;
}

void SLErase(Seqlist* s, int pos)
{
	assert(s);
	assert(pos >= 0 && pos < s->counst);

	s->counst--;
	for (int i = pos; i < s->counst; i++)
	{
		s->seqlist[i] = s->seqlist[i + 1];
	}

	SLCut(s);

	return;
}